import { getBasePath } from "@/api/public";
import { getData, setData } from "@/utils/data-cache";
import { setLocalData } from "@/utils/data-cache";
import defaultSettings from '@/settings'
import { getCmmSetting } from '@/api/serve/setting';

const state = {
  theme: 'el-theme1',
  basePath: '', //文件基础路径，文件上传使用
  sidebarCollapse: !!Number(getData('sidebar_collapse')),
  lastRequestTime: 0,
  searchLogo: '',
  title: '',
  titleLogo: '',
  searchTitle:'',
  webTitle:'',
  loginBg:'',
  topBg:'',
  searchBg:'',
  copyright:'',
};

const mutations = {
  SET_THEME: (state, theme) => {
    state.theme = theme
  },
  SET_BASE_PATH: (state, path) => {
    state.basePath = path
  },
  TOGGLE_SIDEBAR: state => {
    state.sidebarCollapse = !state.sidebarCollapse;
    setData('sidebar_collapse', Number(state.sidebarCollapse));
  },
  UPDATE_REQUEST_TIME: state => {
    state.lastRequestTime = new Date().getTime();
  },
  SET_SEARCH_LOGO: (state, searchLogo) => {
    state.searchLogo = searchLogo
  },
  SET_TITLE: (state, title) => {
    state.title = title
  },
  SET_TITLE_LOGO: (state, titleLogo) => {
    state.titleLogo = titleLogo
  },
  SET_SEARCH_TITLE: (state, searchTitle) => {
    state.searchTitle = searchTitle
  },
  SET_WEB_TITLE: (state, webTitle) => {
    state.webTitle = webTitle
  },
  SET_LOGIN_BG: (state, loginBg) => {
    state.loginBg = loginBg
  },
  SET_TOP_BG: (state, topBg) => {
    state.topBg = topBg
  },
  SET_SEARCH_BG: (state, searchBg) => {
    state.searchBg = searchBg
  },
  SET_COPYRIGHT: (state, copyright) => {
    state.copyright = copyright
  },
};

const actions = {
  async setBasePath({ commit }) {
    let path = await getBasePath();
    commit('SET_BASE_PATH', path.data)
  },
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  updateRequestTime({ commit }) {
    commit('UPDATE_REQUEST_TIME')
  },
  changeTheme({ commit }, theme) {
    let themeArr = Object.keys(defaultSettings.presetDictionary.theme)
    if (!theme || themeArr.indexOf(theme) === -1) {
      theme = themeArr[0]
    }
    commit('SET_THEME', theme);
    document.body.className = theme;
    setLocalData('theme', theme)
  },
  getSysSetting({ commit }) {
    getCmmSetting().then(res => {
      commit('SET_SEARCH_LOGO', res.data.searchLogo);
      commit('SET_TITLE', res.data.title);
      commit('SET_TITLE_LOGO', res.data.titleLogo);
      commit('SET_SEARCH_TITLE', res.data.searchTitle);
      commit('SET_WEB_TITLE', res.data.webTitle);
      document.title=res.data.webTitle
      commit('SET_LOGIN_BG', res.data.loginBg);
      commit('SET_TOP_BG', res.data.topBg);
      commit('SET_SEARCH_BG', res.data.searchBg);
      commit('SET_COPYRIGHT', res.data.copyright);
    })
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

